import React, { useState, useRef, useEffect } from 'react'
import { EChartsOption, ECharts } from 'echarts'
import * as echarts from 'echarts'


// export type EchartProp = {
//     option: EChartsOption,
//     key?: string,
//     style?: {
//         width: string,
//         height: string
//     }
//     className?: string
// }

const removeUndefined = (obj) => {
    for (let key in obj) {
        if (obj === undefined) {
            delete obj[key in obj]
        }
    }
    return obj
}

const Echart = ({ option, key, className, style = { width: '100%', height: '100%' } }) => {

    const chartRef = useRef(null)
    const [echartsInstance, setEchartsInstance] = useState()

    useEffect(() => {
        setEchartsInstance(echarts.init(chartRef.current))
    }, [])

    useEffect(() => {
        const handleResize = () => {
            echartsInstance?.resize()
        }
        window.addEventListener('resize', handleResize)
        return () => {
            window.removeEventListener('resize', handleResize)
        }
    }, [echartsInstance])

    useEffect(() => {
        echartsInstance?.setOption(option)
    }, [echartsInstance, option])

    return (
        <div ref={chartRef} {...removeUndefined({ option, key, className, style })} />
    )
}

export default Echart